//
//  TLMeViewController.m
//  WXReader
//
//  Created by huaya on 2025/3/18.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLMeViewController.h"
#import "TLMeUserTableViewCell.h"
#import "TLMeVipTableViewCell.h"
#import "TLMeBalanceTableViewCell.h"
#import "TLMeSectionsTableViewCell.h"
#import "TL_UserDataViewController.h"
#import "TL_SettingViewController.h"
#import "TLMessageCenterViewController.h"
#import "TLRechargeViewController.h"

#import "TLRechargeHistoryViewController.h"
#import "TLRechargeCoinsViewController.h"

#import "TL_WebViewViewController.h"
#import "CGAboutUs_VC.h"
#import "TL_FeedbackSubViewController.h"
#import "TLWalletViewController.h"
#import "TLRewardsViewController.h"

@interface TLMeViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *titleArr;
@property (nonatomic, strong) NSArray *imgArr;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end

@implementation TLMeViewController

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}
- (UITableView *)tableView{
    if (!_tableView) {
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        footView.backgroundColor = UIColor.clearColor;
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = footView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 15.0, *)) {
            self.tableView.sectionHeaderTopPadding = 0;
        }
        
        [_tableView registerNib:[UINib nibWithNibName:@"TLMeUserTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLMeUserTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TLMeVipTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLMeVipTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TLMeBalanceTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLMeBalanceTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TLMeSectionsTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLMeSectionsTableViewCell"];
        
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
        
        // 隐藏时间文字
        header.lastUpdatedTimeLabel.hidden = YES;
        // 隐藏状态文字
        header.stateLabel.hidden = YES;

        header.lastUpdatedTimeLabel.hidden = YES;
        _tableView.mj_header = header;
        
        
    }
    return _tableView;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    [self getUserData];
}
- (void)loadLastData{
    
    [self getUserData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [TL_ViewHelper setStateBarDefaultStyle];
    
    [self.dataArray addObject:@(TLMineCellType_UserInfo)];
    [self.dataArray addObject:@(TLMineCellType_Vip)];
    [self.dataArray addObject:@(TLMineCellType_Inbox)];
    [self.dataArray addObject:@(TLMineCellType_Rewards)];
    [self.dataArray addObject:@(TLMineCellType_TransctionHistory)];
    [self.dataArray addObject:@(TLMineCellType_HelpCenter)];
    [self.dataArray addObject:@(TLMineCellType_Setting)];
    
    [self.view addGradientBackground];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    self.titleArr = @[WXLocalizedString(@"收件箱"),WXLocalizedString(@"任务中心"),WXLocalizedString(@"交易历史"),WXLocalizedString(@"帮助和反馈"),WXLocalizedString(@"设置")];
    
    self.imgArr = @[@"wd_sjx",@"wd_flzx",@"wd_jyzx",@"wd_bz",@"wd_sz",];
    
    [self getData];
    [_tableView reloadData];
}
- (void)getData{

    [APIManager sendGetRequest:[APIURLManager getLibrary] parameters:@{} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}
- (void)getUserData{
    
    if (!TL_UserInfoManager.isLogin) {
        
        [self.tableView.mj_header endRefreshing];
        [_tableView reloadData];
        
        return;
    }
    
    MJWeakSelf
    
    [APIManager sendGetRequest:[APIURLManager getUserInfo] parameters:nil model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            NSLog(@"%@",requestModel);
            
            TL_UserInfoModel *usermodel = [TL_UserInfoModel mj_objectWithKeyValues:requestModel.data[@"userInfo"]];

            NSDictionary *userDataDict = [usermodel mj_keyValues];
            
            [[NSUserDefaults standardUserDefaults] setObject:userDataDict forKey:@"UserInfoModelDict"];
            
            TL_UserInfoManager.updateWithDict(requestModel.data[@"userInfo"]);
            
            [weakSelf.tableView reloadData];
            
            [weakSelf.tableView.mj_header endRefreshing];
            
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg ?: WXLocalizedString(@"请求失败")];
            if (requestModel.code == 302) {
                [TL_UserInfoManager logout];
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"%@",error);
        
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}
#pragma mark - table delegate - datasource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MJWeakSelf
    
    NSNumber * type = self.dataArray[indexPath.row];
    
    if (type.intValue == TLMineCellType_UserInfo) {
        TLMeUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLMeUserTableViewCell"];
        
        [cell reloadView];
        
        cell.didSelectedBlock = ^{
            
            if (!TL_UserInfoManager.isLogin) {
                [TL_LoginViewController presentLoginView:nil];
            }else{
                [weakSelf.navigationController pushViewController:[[TL_UserDataViewController alloc] init] animated:YES];
            }
            
        };
        
        return cell;
    }else if (type.intValue == TLMineCellType_Vip) {
        TLMeVipTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLMeVipTableViewCell"];
        [cell reloadView];
        cell.rechargeBlock = ^{
            [weakSelf gotoVipView];
        };
        cell.myWalletBlock = ^{
            [weakSelf gotoCointView];
        };
        return cell;
    }else if (type.intValue == TLMineCellType_Balance) {
        TLMeBalanceTableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"TLMeBalanceTableViewCell"];
        
        if (TL_UserInfoManager.isLogin) {
            cell.coinsNumbLab.text = [NSString stringWithFormat:@"%@",TL_UserInfoManager.userInfo.coinNum];
        }else{
            cell.coinsNumbLab.text = @"0";
        }
        
        cell.rechargeBlock = ^{
            [weakSelf gotoCointView];
        };
        cell.detailsBlock = ^{
            [weakSelf gotoOrderDetialsView];
        };
        return cell;
    }else{
        
        TLMeSectionsTableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"TLMeSectionsTableViewCell"];
        
        cell.titleLab.text = self.titleArr[indexPath.row-2];
        [cell.iconImgView setImage:[UIImage imageNamed:self.imgArr[indexPath.row-2]]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [cell.bgView addRoundingCornersWithRoundingCorners:UIRectCornerAllCorners andCornerRadii:0];
            if (cell.titleLab.text == WXLocalizedString(@"收件箱")) {
                [cell.bgView addRoundingCornersWithRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight andCornerRadii:10];
            }else if (cell.titleLab.text == WXLocalizedString(@"设置")) {
                [cell.bgView addRoundingCornersWithRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight andCornerRadii:10];
            }
        });
        return cell;
        
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSNumber * type = self.dataArray[indexPath.row];
    
    switch (type.intValue) {
        case TLMineCellType_UserInfo:
        {
            return 106;
        }
            break;
        case TLMineCellType_Vip:
        {
            return 135;
        }
            break;
        default:
        {
            return 56;
        }
            break;
    }
    
    return 44;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSNumber * type = self.dataArray[indexPath.row];
    
    switch (type.intValue) {
        case TLMineCellType_Inbox:
        {
            TLMessageCenterViewController *vc = [[TLMessageCenterViewController alloc] init];
            
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case TLMineCellType_TransctionHistory:
        {
            TLRechargeHistoryViewController *vc = [[TLRechargeHistoryViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case TLMineCellType_HelpCenter:
        {
            
            if (!TL_UserInfoManager.isLogin) {
                [TL_LoginViewController presentLoginView:nil];
                return;
            }else{
                TL_FeedbackSubViewController *vc = [TL_FeedbackSubViewController new];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        }
            break;
        case TLMineCellType_Setting:
        {
            TL_SettingViewController* vc = [[TL_SettingViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case TLMineCellType_Rewards:
        {
            TLRewardsViewController *vc = [TLRewardsViewController new];
            [[TL_ViewHelper getCurrentViewController].navigationController pushViewController:vc animated:YES];
        }
            break;
            
        default:
            break;
    }
}
- (void)gotoVipView{
    TLRechargeViewController *vc = [[TLRechargeViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)gotoCointView{
    
    if (!TL_UserInfoManager.isLogin) {
        [TL_LoginViewController presentLoginView:nil];
        return;
    }
    
    TLWalletViewController * vc = [TLWalletViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)gotoOrderDetialsView{
    TLRechargeHistoryViewController *vc = [[TLRechargeHistoryViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
@end
